package com.example.chatroom.controller;

import com.example.chatroom.utils.UUIDUtils;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@RequestMapping("/file")
@RestController
public class FileController {

    private String fileStorePath = "E:/1CustomedApp/practise/java/chatroom/outputHere/";

    @PostMapping("/upload")
    public boolean uploadFlie(@RequestParam("file")MultipartFile file, HttpServletRequest request) throws IOException{
        String uploaderName = request.getParameter("uploaderName");
        String uploaderEmail = request.getParameter("uploaderEmail");
        String domain = request.getParameter("domain");
        String fileName = file.getOriginalFilename().replace("_","" );
        int size = (int) (file.getSize()/1024);

        //获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //转换文件名称： domain + uuid
        StringBuilder finalName = new StringBuilder(domain);
        finalName.append("_").append(fileName).append(UUIDUtils.getUUID()).append(suffix);

        File dest = new File(fileStorePath + fileName);
        if(!dest.exists()){
            System.out.println("no no no, there is no file!");
        }
        else System.out.println(" yeah yeah yeah ,there it is.");
        file.transferTo(dest);
        return true;
    }

    @PostMapping("batchUpload")
    public String batchUpload(MultipartHttpServletRequest request){
        List<MultipartFile> files = request.getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); i++) {
            file = files.get(i);
            String filePath = "f:/upload/";
            if (!file.isEmpty()){
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(new File(filePath+file.getOriginalFilename())));
                    stream.write(bytes);
                    stream.close();
                } catch (IOException e) {
                    stream = null;
                    return "第"+i+"个文件上传失败："+e.getMessage();
                }
            }else {
                return "第"+i+"个文件上传失败因为文件为空";
            }
        }
        return "上传成功";
    }

    @GetMapping("/download")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
        String fileName = "boss.jpg";// 文件名
        if (fileName != null) {
            //设置文件路径
            File file = new File("f:/upload/boss.jpg");
            //File file = new File(realPath , fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败";
    }
}
